"""
jackson.chord.views.admin

Views exposing the admin API in chord.admin_api

NOTE: These views should be simple wrappers, because the admin API is accessible programmatically too.
"""
### Start of imports

# This line just better work...
from jackson import debug

# There's debug stuff for the rest
debug.pre_import(__name__)

debug.importing(__name__, 'ext_json')
import jackson.extjson.ext_json as json

debug.importing(__name__, 'HttpResponse from django.http', 2)
from django.http import HttpResponse

debug.importing(__name__, 'chord.admin_api')
import chord.admin_api as admin_api

debug.importing(__name__, 'chord.core')
import chord.core as core

debug.importing(__name__, 'Server from jackson.chord')
from jackson.chord import Server

debug.post_import(__name__)

### End of imports

def init_ring_handler(request):
    context = [__name__, 'init_ring_handler()']
    debug.enter(context, None, 2)
    b = admin_api.init_ring()
    response = HttpResponse(json.dumps(b))
    debug.leave(context, { 'b' : b }, 2)
    return response

def join_ring_handler(request, ip = None, port = None):
    """ @change: replaced settings.ip with ip, settings.port with port
    """
    context = [__name__, 'join_ring_handler()']
    debug.enter(context, None, 2)
    try:
        # build the Server object (the one that we're going to join) 
        s = Server() 
        s.ip = str(ip) # str() added because ip is unicode
        s.port = int(port)
        s.status = 'A'
        s.key = core.generate_server_key(ip, port)
        b = admin_api.join_ring(s)
        response = HttpResponse(json.dumps(b))
    except Exception, e:
        s = "<h1>chord.views.admin: problem is as follows: " + str(e) +". args: "+ str(e.args) + "</h1>"
        debug.exception(context, str(e))
        response = HttpResponse(s)
    debug.leave(context, { 'b' : b }, 2)
    return response

def leave_ring_handler(request):
    context = [__name__, 'leave_ring_handler()']
    debug.enter(context, None, 2)
    b = admin_api.leave_ring() # returns true or false__name__, 'leave_ring_handler()'
    response = HttpResponse(json.dumps(b))
    debug.leave(context, { 'b' : b }, 2)
    return response

def whoami_handler(request):
    context = [__name__, 'whoam_handler()']
    debug.enter(context, None)
    me = core.get_me()
    pred = core.get_predecessor()
    succ = core.get_successor()
    response = HttpResponse(json.dumps({ 'me' : me, 'predecessor' : pred, 'successor' : succ }))
    debug.leave(context, { 'me' : me, 'predecessor' : pred, 'successor' : succ })
    return response

def lookup_handler(request, key=None):
    context = [__name__, 'lookup_handler()']
    debug.enter(context, None)
    server = core.find_successor(key)
    response = HttpResponse(json.dumps({ 'successor' : server }))
    debug.leave(context, { 'successor' : server })
    return response
